<template>
  <view class="booking-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <text class="iconfont icon-back">←</text>
      </view>
      <view class="title">门票预订</view>
      <view class="more-btn"></view>
    </view>
    
    <!-- 景点信息 -->
    <view class="scenic-info">
      <image :src="scenic.images[0]" mode="aspectFill" class="scenic-image"></image>
      <view class="info">
        <view class="name">{{ scenic.name }}</view>
        <view class="ticket-name">{{ ticket.name }}</view>
        <view class="price">
          <text class="price-symbol">¥</text>
          <text class="price-value">{{ ticket.price }}</text>
        </view>
      </view>
    </view>

    <!-- 选择日期 -->
    <view class="booking-section">
      <view class="section-title">使用日期(当地时间)</view>
      <view class="date-picker">
        <view 
          v-for="(date, index) in availableDates" 
          :key="index" 
          class="date-item" 
          :class="{ active: selectedDateIndex === index }"
          @tap="selectDate(index)"
        >
          <view class="date-day">{{ date.label }}</view>
          <view class="date-value">{{ date.date }}</view>
          <view class="date-price">
            <text>¥ {{ ticket.price }}</text>
          </view>
          <view class="date-check" v-if="selectedDateIndex === index">✓</view>
        </view>
        <view class="date-more">
          <text>更多</text>
        </view>
      </view>
    </view>
    
    <!-- 选择数量 -->
    <view class="booking-section">
      <view class="section-title">数量</view>
      <view class="quantity-picker">
        <view class="quantity-btn minus" @tap="decreaseQuantity">-</view>
        <view class="quantity-value">{{ quantity }}</view>
        <view class="quantity-btn plus" @tap="increaseQuantity">+</view>
      </view>
    </view>
    
    <!-- 购买须知 -->
    <view class="booking-section">
      <view class="section-title">购买须知</view>
      <view class="booking-notes">
        <view class="note-item">
          <view class="note-title">有效期</view>
          <view class="note-content">{{ ticket.valid }}</view>
        </view>
        <view class="note-item">
          <view class="note-title">使用时间</view>
          <view class="note-content">{{ scenic.openTime }}</view>
        </view>
        <view class="note-item">
          <view class="note-title">退款政策</view>
          <view class="note-content">使用前1天可全额退款，使用当天不可退款</view>
        </view>
      </view>
    </view>
    
    <!-- 联系人信息 -->
    <view class="booking-section">
      <view class="section-title">联系人信息</view>
      <view class="contact-info">
        <view class="input-item">
          <text class="label">姓名</text>
          <input type="text" v-model="contactName" placeholder="请输入姓名" />
        </view>
        <view class="input-item">
          <text class="label">手机号</text>
          <input type="number" v-model="contactPhone" placeholder="请输入手机号" maxlength="11" />
        </view>
      </view>
    </view>
    
    <!-- 底部结算栏 -->
    <view class="bottom-bar">
      <view class="price-info">
        <text class="total-label">总价</text>
        <view class="total-price">
          <text class="price-symbol">¥</text>
          <text class="price-value">{{ totalPrice }}</text>
        </view>
        <text class="price-detail" @tap="showPriceDetail">明细 ▼</text>
      </view>
      <view class="submit-btn" @tap="submitOrder">提交订单</view>
    </view>
    
    <!-- 价格明细弹窗 -->
    <view class="price-detail-popup" v-if="showPriceDetailPopup">
      <view class="popup-mask" @tap="hidePriceDetail"></view>
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">价格明细</text>
          <text class="popup-close" @tap="hidePriceDetail">×</text>
        </view>
        <view class="popup-body">
          <view class="detail-item">
            <text class="detail-label">{{ ticket.name }} x {{ quantity }}</text>
            <text class="detail-value">¥{{ ticket.price * quantity }}</text>
          </view>
          <view class="detail-divider"></view>
          <view class="detail-item total">
            <text class="detail-label">总计</text>
            <text class="detail-value">¥{{ totalPrice }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 支付方式弹窗 -->
    <view class="payment-popup" v-if="showPaymentPopup">
      <view class="popup-mask" @tap="cancelPayment"></view>
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">选择支付方式</text>
          <text class="popup-close" @tap="cancelPayment">×</text>
        </view>
        <view class="popup-body">
          <view class="payment-option" @tap="selectPayment('wechat')">
            <view class="payment-icon wechat">
              <text class="icon-text">微信</text>
            </view>
            <text class="payment-name">微信支付</text>
            <text class="payment-check" v-if="paymentMethod === 'wechat'">✓</text>
          </view>
          <view class="payment-option" @tap="selectPayment('alipay')">
            <view class="payment-icon alipay">
              <text class="icon-text">支付宝</text>
            </view>
            <text class="payment-name">支付宝</text>
            <text class="payment-check" v-if="paymentMethod === 'alipay'">✓</text>
          </view>
        </view>
        <view class="payment-btn" @tap="confirmPayment">确认支付 ¥{{ totalPrice }}</view>
      </view>
    </view>
  </view>
</template>

<script>
import { checkNeedLogin, getUserInfo } from '../../utils/auth.js';

export default {
  data() {
    return {
      scenicId: 0,
      ticketId: 0,
      scenic: {
        name: '',
        images: []
      },
      ticket: {
        name: '',
        price: 0,
        valid: ''
      },
      availableDates: [],
      selectedDateIndex: 0,
      quantity: 1,
      contactName: '',
      contactPhone: '',
      showPriceDetailPopup: false,
      showPaymentPopup: false,
      paymentMethod: 'wechat',
      userInfo: null
    }
  },
  computed: {
    totalPrice() {
      return this.ticket.price * this.quantity;
    },
    selectedDate() {
      return this.availableDates[this.selectedDateIndex]?.fullDate || '';
    }
  },
  onLoad(option) {
    // 检查登录状态
    if (checkNeedLogin()) return;
    
    // 获取传递的景点ID和票ID
    this.scenicId = option.scenicId || 1;
    this.ticketId = option.ticketId || 1;
    
    // 获取用户信息
    this.getUserData();
    
    // 加载景点和票务信息
    this.loadTicketData();
    
    // 生成可用日期
    this.generateAvailableDates();
  },
  methods: {
    // 获取用户信息
    getUserData() {
      this.userInfo = getUserInfo();
      if (this.userInfo) {
        this.contactName = this.userInfo.nickName || '';
        this.contactPhone = this.userInfo.phone || '';
      }
    },
    
    // 加载票务数据
    loadTicketData() {
      // 这里应该调用接口获取数据，现在使用模拟数据
      // 构建的景点数据映射表
      const scenicData = {
        1: {
          name: '故宫博物院',
          images: [
            'http://114.55.56.174:19000/shzy/故宫.jpg',
            'http://114.55.56.174:19000/shzy/故宫1.png',
            'http://114.55.56.174:19000/shzy/故宫2.png'
          ],
          tickets: [
            {
              id: 1,
              name: '成人票',
              desc: '标准门票',
              valid: '有效期：购买后7天内有效',
              price: 60
            },
            {
              id: 2,
              name: '学生票',
              desc: '需持有效学生证',
              valid: '有效期：购买后7天内有效',
              price: 30
            }
          ],
          openTime: '8:30-17:00 (16:00停止售票)'
        },
        // 添加更多景点...
      };
      
      // 获取景点信息
      this.scenic = scenicData[this.scenicId] || {};
      
      // 获取票务信息
      if (this.scenic.tickets) {
        this.ticket = this.scenic.tickets.find(t => t.id == this.ticketId) || this.scenic.tickets[0];
      }
    },
    
    // 生成可用日期
    generateAvailableDates() {
      const dayNames = ['今天', '明天', '后天'];
      const dayOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      
      const dates = [];
      const today = new Date();
      
      // 生成5天的可用日期
      for (let i = 0; i < 5; i++) {
        const date = new Date(today);
        date.setDate(today.getDate() + i);
        
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const fullDate = `${date.getFullYear()}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
        
        dates.push({
          label: i < 3 ? dayNames[i] : dayOfWeek[date.getDay()],
          date: `${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`,
          fullDate: fullDate
        });
      }
      
      this.availableDates = dates;
    },
    
    // 选择日期
    selectDate(index) {
      this.selectedDateIndex = index;
    },
    
    // 增加数量
    increaseQuantity() {
      if (this.quantity < 10) {
        this.quantity++;
      } else {
        uni.showToast({
          title: '每单最多可购买10张票',
          icon: 'none'
        });
      }
    },
    
    // 减少数量
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--;
      }
    },
    
    // 显示价格明细
    showPriceDetail() {
      this.showPriceDetailPopup = true;
    },
    
    // 隐藏价格明细
    hidePriceDetail() {
      this.showPriceDetailPopup = false;
    },
    
    // 提交订单
    submitOrder() {
      // 表单验证
      if (!this.contactName.trim()) {
        uni.showToast({
          title: '请填写联系人姓名',
          icon: 'none'
        });
        return;
      }
      
      if (!this.contactPhone.trim() || !/^1\d{10}$/.test(this.contactPhone)) {
        uni.showToast({
          title: '请填写正确的手机号',
          icon: 'none'
        });
        return;
      }
      
      // 显示支付方式弹窗
      this.showPaymentPopup = true;
    },
    
    // 选择支付方式
    selectPayment(method) {
      this.paymentMethod = method;
    },
    
    // 取消支付
    cancelPayment() {
      this.showPaymentPopup = false;
    },
    
    // 确认支付
    confirmPayment() {
      // 生成订单数据
      const orderData = {
        id: Date.now().toString(), // 简单使用时间戳作为订单ID
        userId: this.userInfo?.userId || 'guest',
        userName: this.userInfo?.nickName || 'guest',
        scenicId: this.scenicId,
        scenicName: this.scenic.name,
        ticketId: this.ticketId,
        ticketName: this.ticket.name,
        price: this.ticket.price,
        quantity: this.quantity,
        totalAmount: this.totalPrice,
        visitDate: this.selectedDate,
        contactName: this.contactName,
        contactPhone: this.contactPhone,
        createTime: new Date().toISOString(),
        status: 'pending', // pending, paid, cancelled
        paymentMethod: this.paymentMethod
      };
      
      console.log('生成订单：', orderData);
      
      // 调用支付
      this.processPayment(orderData);
    },
    
    // 处理支付
    processPayment(orderData) {
      // 关闭支付弹窗
      this.showPaymentPopup = false;
      
      // 显示支付加载
      uni.showLoading({
        title: '支付处理中...'
      });
      
      // 模拟支付过程
      setTimeout(() => {
        uni.hideLoading();
        
        // 获取现有订单
        let orders = uni.getStorageSync('userOrders') || [];
        
        // 添加新订单
        const newOrder = {
          ...orderData,
          status: 'paid',
          payTime: new Date().toISOString()
        };
        
        orders.push(newOrder);
        
        // 保存订单
        uni.setStorageSync('userOrders', orders);
        
        // 显示支付成功
        uni.showToast({
          title: '支付成功',
          icon: 'success'
        });
        
        // 跳转到订单详情页
        setTimeout(() => {
          uni.redirectTo({
            url: '/pages/user/orders/detail?orderId=' + newOrder.id
          });
        }, 1500);
      }, 2000);
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    }
  }
}
</script>

<style lang="scss">
.booking-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 100;
  
  .back-btn, .more-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .iconfont {
      font-size: 40rpx;
      color: #333;
    }
  }
  
  .title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.scenic-info {
  display: flex;
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .scenic-image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 8rpx;
    margin-right: 20rpx;
  }
  
  .info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    
    .name {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .ticket-name {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 20rpx;
    }
    
    .price {
      display: flex;
      align-items: baseline;
      
      .price-symbol {
        font-size: 24rpx;
        color: #ff4d4f;
      }
      
      .price-value {
        font-size: 40rpx;
        font-weight: bold;
        color: #ff4d4f;
      }
    }
  }
}

.booking-section {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
}

.date-picker {
  display: flex;
  overflow-x: auto;
  
  .date-item {
    min-width: 160rpx;
    height: 180rpx;
    background: #f9f9f9;
    border-radius: 8rpx;
    margin-right: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 0;
    position: relative;
    border: 2rpx solid transparent;
    flex-shrink: 0;
    
    &.active {
      background: #f0f8ff;
      border-color: #4080ff;
    }
    
    .date-day {
      font-size: 28rpx;
      color: #333;
    }
    
    .date-value {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .date-price {
      font-size: 24rpx;
      color: #ff4d4f;
    }
    
    .date-check {
      position: absolute;
      right: 10rpx;
      top: 10rpx;
      width: 40rpx;
      height: 40rpx;
      border-radius: 50%;
      background: #4080ff;
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24rpx;
    }
  }
  
  .date-more {
    min-width: 80rpx;
    height: 180rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    text {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.quantity-picker {
  display: flex;
  align-items: center;
  
  .quantity-btn {
    width: 60rpx;
    height: 60rpx;
    border-radius: 30rpx;
    background: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 40rpx;
    color: #333;
  }
  
  .quantity-value {
    margin: 0 30rpx;
    font-size: 32rpx;
    color: #333;
    min-width: 60rpx;
    text-align: center;
  }
}

.booking-notes {
  .note-item {
    margin-bottom: 20rpx;
    
    .note-title {
      font-size: 26rpx;
      color: #999;
      margin-bottom: 10rpx;
    }
    
    .note-content {
      font-size: 28rpx;
      color: #333;
    }
  }
}

.contact-info {
  .input-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #eee;
    
    .label {
      width: 140rpx;
      font-size: 28rpx;
      color: #333;
    }
    
    input {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }
  }
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .price-info {
    flex: 1;
    display: flex;
    align-items: baseline;
    
    .total-label {
      font-size: 28rpx;
      color: #333;
      margin-right: 10rpx;
    }
    
    .total-price {
      display: flex;
      align-items: baseline;
      
      .price-symbol {
        font-size: 24rpx;
        color: #ff4d4f;
      }
      
      .price-value {
        font-size: 40rpx;
        font-weight: bold;
        color: #ff4d4f;
      }
    }
    
    .price-detail {
      margin-left: 20rpx;
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .submit-btn {
    width: 240rpx;
    height: 80rpx;
    background: #4080ff;
    color: #fff;
    font-size: 32rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 40rpx;
  }
}

.price-detail-popup, .payment-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  
  .popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
  }
  
  .popup-content {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    border-radius: 20rpx 20rpx 0 0;
    overflow: hidden;
    
    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1rpx solid #eee;
      
      .popup-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .popup-close {
        font-size: 40rpx;
        color: #999;
      }
    }
    
    .popup-body {
      padding: 30rpx;
      
      .detail-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;
        
        .detail-label {
          font-size: 28rpx;
          color: #666;
        }
        
        .detail-value {
          font-size: 28rpx;
          color: #333;
        }
        
        &.total {
          margin-top: 20rpx;
          
          .detail-label {
            font-size: 32rpx;
            color: #333;
            font-weight: bold;
          }
          
          .detail-value {
            font-size: 32rpx;
            color: #ff4d4f;
            font-weight: bold;
          }
        }
      }
      
      .detail-divider {
        height: 2rpx;
        background: #eee;
        margin: 20rpx 0;
      }
      
      .payment-option {
        display: flex;
        align-items: center;
        padding: 30rpx 0;
        border-bottom: 1rpx solid #eee;
        
        .payment-icon {
          width: 80rpx;
          height: 80rpx;
          border-radius: 8rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 20rpx;
          
          .icon-text {
            color: #fff;
            font-size: 24rpx;
          }
          
          &.wechat {
            background: #09bb07;
          }
          
          &.alipay {
            background: #1677ff;
          }
        }
        
        .payment-name {
          flex: 1;
          font-size: 28rpx;
          color: #333;
        }
        
        .payment-check {
          width: 40rpx;
          height: 40rpx;
          border-radius: 50%;
          background: #4080ff;
          color: #fff;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24rpx;
        }
      }
    }
    
    .payment-btn {
      margin: 30rpx;
      height: 90rpx;
      background: #4080ff;
      color: #fff;
      font-size: 32rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 45rpx;
    }
  }
}
</style> 